#include <stdlib.h>
#include "MIRole.h"

namespace MIRole {

int getComponent(const Collaboration::MIRole& r, const ::std::string& name)
{
	unsigned int i=0;
	Collaboration::MIComponent aux;

	for (i=0; i<r.components.size(); i++)
	{
		aux = r.components[i];
		if (aux.name == name)
		{
			return i;
		}
	}

	return -1;
}

void isOnline(Collaboration::MIRole& r, bool b)
{
	r.isOnline = b;
	if (r.isOnline)
		r.lastTimeUpdated = time(0);
}

bool hasAllowedRole(const Collaboration::MIRole& r, const ::std::string& role)
{
	unsigned int i;
	
	if (role.empty()) return false;
	
	for(i=0; i<r.allowedRoles.size(); i++)
	{
		if (r.allowedRoles[i] == role)
			return true;
	}

	return false;
}

bool addAllowedRole(Collaboration::MIRole& r, const ::std::string& role)
{
	if (!hasAllowedRole(r, role))
	{
		r.allowedRoles.push_back(role);

		return true;
	}

	else return false;
}

bool removeAllowedRole(Collaboration::MIRole& r, const ::std::string& role)
{
	::std::string temp;
	unsigned int i;
	for (i=0; i<r.allowedRoles.size(); i++)
	{
		if (r.allowedRoles[i] == role)
		{
			temp = r.allowedRoles[r.allowedRoles.size()-1];
			r.allowedRoles[r.allowedRoles.size()-1] = r.allowedRoles[i];
			r.allowedRoles[i] = temp;
			
			r.allowedRoles.pop_back(); 
			
			return true;
		}
	}

	return false;
}

int getComponentPermissions(const Collaboration::MIRole& r, const ::std::string& comp_name)
{
	int pos = getComponent(r, comp_name);
	if (pos != -1)
	{
		return r.components[pos].permissions;
	}

	else return -1;
}

void setComponentPermissions(Collaboration::MIRole& r, const ::std::string& comp_name, int level)
{
	int pos = getComponent(r, comp_name);

	if (pos != -1)
	{
		r.components[pos].permissions = level;
	}

	else
	{
		Collaboration::MIComponent aux;
		aux.name = comp_name;
		aux.permissions = level;
		
		r.components.push_back(aux);
	}
}

}
